package com.jh.paymentchannel.huizhi;

import cn.jh.common.utils.CommonConstants;
import com.jh.paymentchannel.util.SignUtils;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@EnableAutoConfiguration
public class HuiZhiQuickCallBackService {

    @Autowired
    private Util util;

    //@Value("${huizhi.merKey}")
    private String merKey;

    private static final Logger log = LoggerFactory.getLogger(HuiZhiQuickCallBackService.class);

    //5支付结果通知
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/pay/hz/notify_call")
    public void payNotice(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取参数
        log.info("交易结果异步通知调用！！！！！！！！！！！！！！！！！！！！！！！！！！！！");
        String merId = request.getParameter("merId");
        String merOrderId = request.getParameter("merOrderId");
        String orderDate = request.getParameter("orderDate");
        String tranAmt = request.getParameter("tranAmt");
        String settStat = request.getParameter("settStat");
        String resCdoe = request.getParameter("resCdoe");
        String resMsg = request.getParameter("resMsg");
        String sign = request.getParameter("sign");
        HashMap<Object, Object> map = new HashMap<>();

        try {
            //验签sign
            String md5Datas = verSign(merId, merOrderId, orderDate, tranAmt, settStat, resCdoe, resMsg);
            if (sign != null && !"".equals(sign)) {
                log.info("参数不为空");
                if (md5Datas.equals(sign)) {
                    log.info("验签成功");
                    RestTemplate restTemplate = new RestTemplate();

                    URI uri = util.getServiceUrl("transactionclear", "error url request!");
                    String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";

                    /**根据的用户手机号码查询用户的基本信息*/
                    MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("order_code", merOrderId);
                    String result = restTemplate.postForObject(url, requestEntity, String.class);
                    JSONObject jsonObject = JSONObject.fromObject(result);
                    JSONObject resultObj = jsonObject.getJSONObject("result");
                    String ordercode = resultObj.getString("ordercode");

                    log.info("订单号===============================" + ordercode);
                    /**更新订单状态*/
                    /**调用下单，需要得到用户的订单信息*/
                    restTemplate = new RestTemplate();

                    URI uris = util.getServiceUrl("transactionclear", "error url request!");
                    String urls = uris.toString() + "/v1.0/transactionclear/payment/update";

                    /**根据的用户手机号码查询用户的基本信息*/
                    requestEntity = new LinkedMultiValueMap<String, String>();
                    if (resCdoe != null && "0000".equals(resCdoe)) {
                        requestEntity.add("order_code", ordercode);
                        requestEntity.add("direct_clearing", "0");
                        requestEntity.add("status", "1");
                    }
                    result = restTemplate.postForObject(urls, requestEntity, String.class);
               /*     jsonObject = JSONObject.fromObject(result);
                    resultObj = jsonObject.getJSONObject("result");*/
                  /*  log.info("更新订单结果==========="+resultObj.getString(CommonConstants.RESP_CODE));
                    log.info(resultObj.getString(CommonConstants.RESULT));*/
                    /**判断是否有外放的通道的处理， 如果有那么继续回调外放哦*/
                    uri = util.getServiceUrl("transactionclear", "error url request!");
                    url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";


                    requestEntity = new LinkedMultiValueMap<String, String>();
                    requestEntity.add("order_code", ordercode);
                    result = restTemplate.postForObject(url, requestEntity, String.class);

                    jsonObject = JSONObject.fromObject(result);
                    resultObj = jsonObject.getJSONObject("result");
                    String outMerOrdercode = resultObj.getString("outMerOrdercode");
                    String orderdesc = resultObj.getString("desc");
                    String phone = resultObj.getString("phone");
                    String tranamount = resultObj.getString("amount");
                    String channelTag = resultObj.getString("channelTag");
                    String notifyURL = resultObj.getString("outNotifyUrl");
                    if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
                        uri = util.getServiceUrl("channel", "error url request!");
                        url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
                        requestEntity = new LinkedMultiValueMap<String, String>();
                        requestEntity.add("merchant_no", phone);
                        requestEntity.add("amount", tranamount);
                        requestEntity.add("channel_tag", channelTag);
                        requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
                        requestEntity.add("order_code", outMerOrdercode);
                        requestEntity.add("sys_order", ordercode);
                        requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
                        result = restTemplate.postForObject(url, requestEntity, String.class);
                    }
                    response.getWriter().write("success");

                } else {
                    log.info("验签失败");
                }

            } else {
                log.info("签名参数为空");
            }

        } catch (Exception e) {
            log.info("回调异常:" + e.getMessage() + e);

        }


    }

    /*惠志返回app的页面地址*/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/huizhi/return_call")
    public String miLianReturnCallback(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        log.info("惠志回到页面------------------------------------------------------");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        return "huizhiquickReturnPage";
    }

    /**
     * 验签
     *
     * @param merId
     * @param merOrderId
     * @param orderDate
     * @param tranAmt
     * @param settStat
     * @param resCdoe
     * @param resMsg
     * @return
     */
    private String verSign(String merId, String merOrderId, String orderDate, String tranAmt, String settStat, String resCdoe, String resMsg) throws Exception {
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("merId", merId));
        nvps.add(new BasicNameValuePair("merOrderId", merOrderId));
        nvps.add(new BasicNameValuePair("orderDate", orderDate));
        nvps.add(new BasicNameValuePair("tranAmt", tranAmt));
        nvps.add(new BasicNameValuePair("settStat", settStat));
        nvps.add(new BasicNameValuePair("resCdoe", resCdoe));
        nvps.add(new BasicNameValuePair("resMsg", resMsg));

        String md5Datas = SignUtils.signMD5Datas(nvps, merKey);
        return md5Datas;
    }
}
